package com.onemile.app;

import java.util.ArrayList;

import android.R.integer;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.onemile.app.base.BaseUI;
import com.onemile.controls.AdpLV_CommodityList;
import com.onemile.controls.AdpLV_FavoriteList;
import com.onemile.data.DXml;
import com.onemile.data.DXml.FieldList;
import com.onemile.entity.PubConst;
import com.onemile.entity.Session;
import com.onemile.entity.model.ECommodity;
import com.onemile.entity.model.EFavorite;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiDialogsFactory;

public class UIFavoriteList extends BaseUI
{
   private ListView listView;
   private ArrayList<Object> loadedPageList;
   private LayoutInflater mInflater;
   private AdpLV_FavoriteList adpFavoriteList;
   private ImageView imgLeftLocation;
   private ImageView imgMiddleType;
   private ImageView imgRightPrice;
   private ImageView imgTopInfoBG;

   private int CurrentShopType=0;
   private int CurrentType=1;
   private ImageView imgCancelFavorite;

   
   // 分页需要的=========Begin==============================================
   private View footLoadingView;
   private TextView txtNoData;

   private int MaxDateNum;// 设置一个最大的数据条数，超过即不再加载
   private int lastVisibleIndex; // 最后可见条目的索引
   private int nextPageNum = 1;

   public void CleanPageList()
   {
	  nextPageNum = 1;
	  loadedPageList.clear();
   }
   // 分页需要的=========END==============================================
   
   
   private void InitControls()
   {
	  // 分页需要的=========Begin==============================================
	  mInflater = LayoutInflater.from(this);
	  footLoadingView = mInflater.inflate(R.layout.listview_moredata, null);
	  txtNoData = (TextView)mInflater.inflate(R.layout.all_no_data_txt,null);
	  loadedPageList = new ArrayList<Object>();
	  // 分页需要的=========END==============================================

	  imgCancelFavorite = (ImageView) findViewById(R.id.imgCancelFav_favorite_item);
	  imgTopInfoBG = (ImageView) findViewById(R.id.imgBG_topinfo_btn);
	  imgLeftLocation = (ImageView) findViewById(R.id.imgLeft_topinfo_btn);
	  imgLeftLocation.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			imgTopInfoBG.setImageResource(R.drawable.top_info_fav_left);
			CurrentType = 1;
			CurrentShopType=0;
			RunThread(true, CurrentType, CurrentShopType);
		 }
	  });
	  imgMiddleType = (ImageView) findViewById(R.id.imgMiddle_topinfo_btn);
	  imgMiddleType.setOnClickListener(new View.OnClickListener()
	  {                   
		 @Override
		 public void onClick(View v)
		 {
			imgTopInfoBG.setImageResource(R.drawable.top_info_fav_middle);
			CurrentType = 2;
			int currentSelect=0;
			switch (CurrentShopType)
			{
			   case 1:
				  currentSelect=0;
				  break;
			   case 2: 
				  currentSelect=1;
				  break;
			   case 4:
				  currentSelect=2;
				  break;
			   default:
				  currentSelect=0;
				  break;
			}
			UtiDialogsFactory.getInstance().ShowSingleSelectItemDialog(UIFavoriteList.this, new String[] { "餐馆", "饮料", "便利店" }, currentSelect, new DialogInterface.OnClickListener()
			{
			   @Override
			   public void onClick(DialogInterface dialog, int which)
			   {
				  switch (which)
				  {
					 case 0:
						CurrentShopType = 1;
						break;
					 case 1:
						CurrentShopType = 2;
						break;
					 case 2:
						CurrentShopType = 4;
						break;
				  }
				  RunThread(true, CurrentType, CurrentShopType);
				  dialog.dismiss();
			   }
			});
		 }
	  });
	  imgRightPrice = (ImageView) findViewById(R.id.imgRight_topinfo_btn);
	  imgRightPrice.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			imgTopInfoBG.setImageResource(R.drawable.top_info_fav_right);
			CurrentType = 3;
			CurrentShopType = 0;
			RunThread(true, CurrentType, CurrentShopType);
		 }
	  });

	  listView = (ListView) findViewById(R.id.listView_favorite);
	  // 分页需要的=========Begin==============================================
	  listView.setOnScrollListener(scrollListener);
	  // 分页需要的=========End==============================================
	  listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> arg0, View currentView, int position, long arg3)
		 {
			if (listView.getFooterViewsCount() > 0 && position == listView.getAdapter().getCount() - 1)
			{
			   // 屏蔽掉FootView的单击事件
			}
			else
			{
			   Intent intent = new Intent();
			   intent.setClass(UIFavoriteList.this, UIShopDetails.class);
			   EFavorite listItemData = (EFavorite) listView.getAdapter().getItem(position);
			   intent.putExtra(PubConst.Intent_Key.SHOP_ID, listItemData.getShopsId());
			   startActivity(intent);
			}
		 }
	  });
   }

   /**
    * 
    * @param IsNeedRefresh
    * @param type
    *           1:location 2:商店种类 3:人均消费
    * @param shoptype
    *           当type=2的时候 1：餐馆 2：饮料 4：便利店。当type为其他时输入0
    */
   private void RunThread(boolean IsNeedRefresh, int type, int shoptype)
   {
	  switch (type)
	  {
		 case 1:
			executeAsyncTask(PubConst.TaskName.FAVORITES_LIST_LACTION, new Object[] { IsNeedRefresh });
			break;
		 case 2:
			executeAsyncTask(PubConst.TaskName.FAVORITES_LIST, new Object[] { IsNeedRefresh, 1, 1, shoptype });
			break;
		 case 3:
			executeAsyncTask(PubConst.TaskName.FAVORITES_LIST, new Object[] { IsNeedRefresh, 9, 1, "" });
			break;
	  }
   }

   // 分页需要的=========Begin==============================================
   private OnScrollListener scrollListener = new OnScrollListener()
   {
	  @Override
	  public void onScrollStateChanged(AbsListView view, int scrollState)
	  {
	  }

	  @Override
	  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	  {
		 try
		 {
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
			if (visibleItemCount != 0)
			{
			   if ((firstVisibleItem + visibleItemCount) == totalItemCount)// 表示已经滚动到底部了
			   {
				  nextPageNum = totalItemCount / PubConst.Setting.GOODSLIST_NUM + 1;// 计算当前是第几页数据

				  if (listView.getFooterViewsCount() < 1)// 当没有其他数据加载时，再加载,确保同一时间只运行一个下载线程
				  {
					 if (!loadedPageList.contains(nextPageNum))// 如果没有加载当前页面
					 {
						RunThread(false, CurrentType, CurrentShopType);
					 }
				  }
			   }
			}
		 }
		 catch (Exception e)
		 {
			Log.e(PubConst.Tag.ERROR, "UIFavorite_onScroll()", e);
		 }
	  }
   };

   // 分页需要的=========END==============================================

   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  SetNavigationStatus(2);
	  InitControls();
	  RunThread(false, CurrentType, CurrentShopType);
   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.favorite;
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
	  topTxt.setText(getString(R.string.title_myfavorite)); 
	  leftImBtn.setVisibility(View.INVISIBLE);
	  rightRay.setVisibility(View.VISIBLE);
	  SetRightBtnToCart();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if (taskName.equals(PubConst.TaskName.FAVORITES_LIST)||taskName.equals(PubConst.TaskName.FAVORITES_LIST_LACTION))
	  {
		 // 分页需要的=========Begin==============================================
		 listView.addFooterView(footLoadingView);
		 txtNoData.setVisibility(View.GONE);
		 if ((Boolean) params[0])
		 {
			adpFavoriteList = null;
			listView.setAdapter(null);
			CleanPageList();// 清除已经保存的“已加载页面列表”
		 }
		 if (listView.getChildCount() < 1)// 当列表不存在的时候才显示第一次加载的画面
		 {
			UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIFavoriteList.this, getString(R.string.dialog_loading));
			adpFavoriteList = new AdpLV_FavoriteList(UIFavoriteList.this, new AdpLV_FavoriteList.AdapterCallBack()
			{
			   @Override
			   public void Do(final String UserCollectionId)
			   {
				  UtiDialogsFactory.getInstance().ShowOKCancelAlertDialog(UIFavoriteList.this, getString(R.string.dialog_tips), getString(R.string.fav_confirm_cancel),
						new DialogInterface.OnClickListener()
						{
						   @Override
						   public void onClick(DialogInterface dialog, int which)
						   {
							  executeAsyncTask(PubConst.TaskName.FAVORITE_CANCEL, new Object[] { UserCollectionId });
							  dialog.dismiss();
						   }
						});
			   }
			});
			listView.setAdapter(adpFavoriteList);
			listView.removeFooterView(footLoadingView);
		 }

		 // 分页需要的=========End==============================================
	  }
	  if (taskName.equals(PubConst.TaskName.FAVORITE_CANCEL))
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIFavoriteList.this, getString(R.string.dialog_loading));
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.FAVORITES_LIST))
		 {
			return NetClient.GetFavoriteShopListByUserId_S(Session.getInstance().getUserInfo().getUserId(), nextPageNum, 10, String.valueOf(params[1]), String.valueOf(params[2]),
				  String.valueOf(params[3]));
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.FAVORITES_LIST_LACTION))
		 {
			return NetClient
				  .GetFavoriteShopListByUserId_SL(Session.getInstance().getUserInfo().getUserId(), nextPageNum, 10, Session.getInstance().getLatitude(), Session.getInstance().getLongitude());
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.FAVORITE_CANCEL))
		 {
			return NetClient.CancelFavorite(String.valueOf(params[0]));
		 }

	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIFavoriteList_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.FAVORITES_LIST)||taskName.equals(PubConst.TaskName.FAVORITES_LIST_LACTION))
		 {
			// 分页需要的=========Begin==============================================

			if (result != null)// 有结果
			{
			   DXml data = (DXml) result;
			   ArrayList<EFavorite> list = new ArrayList<EFavorite>();
			   EFavorite favorite = null;
			   int size = data.getBody().getChilds().length;
			   for (int i = 0; i < size; i++)
			   {
				  FieldList fieldList = data.getBody().GetFieldList(i);

				  favorite = new EFavorite();
				  favorite.setShopName(fieldList.GetFieldValue("ShopsName"));
				  favorite.setFavoriteTime(fieldList.GetFieldValue("Rec_CreateTime"));
				  favorite.setRecommendation(fieldList.GetFieldValue("RecommendedDishes"));
				  favorite.setUserCollectionId(fieldList.GetFieldValue("UserCollectionId"));
				  favorite.setShopsId(fieldList.GetFieldValue("ShopsId"));
				  favorite.setFreight(fieldList.GetFieldValue("Freight"));
				  favorite.setOpeningTime(fieldList.GetFieldValue("OpeningTime"));
				  favorite.setClosingTime(fieldList.GetFieldValue("ClosingTime"));
				  favorite.setDeliveryDistance(fieldList.GetFieldValue("DeliveryDistance"));
				  favorite.setLowestPrice(fieldList.GetFieldValue("LowestPrice"));
				  list.add(favorite);
			   }

			   adpFavoriteList.addItem(list);
			   adpFavoriteList.notifyDataSetChanged();
    
			   loadedPageList.add(nextPageNum);
			}
			else
			// 如果没有找到结果又是第一次加载数据。显示 无数据
			{
			   if (listView.getChildCount() < 1 || (listView.getChildCount() == 1 && listView.getFooterViewsCount() == 1))
			   {
				  txtNoData.setVisibility(View.VISIBLE);
			   }
			}
			// 第一次打开时显示
			if (listView.getChildCount() < 1 || (listView.getChildCount() == 1 && listView.getFooterViewsCount() == 1))
			{
			   UtiDialogsFactory.getInstance().DismissLoadingDialog();
			}
			if (listView.getFooterViewsCount() > 0)
			{
			   listView.removeFooterView(footLoadingView);
			}
			// 分页需要的=========End==============================================
		 }
		 if (taskName.equals(PubConst.TaskName.FAVORITE_CANCEL))
		 {
			UtiDialogsFactory.getInstance().DismissLoadingDialog();
			RunThread(true, CurrentType, CurrentShopType);
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIFavoriteList_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }
}
